import json


def convert_to_openai_tools_format(test_data):
    tools = []

    for api in test_data['apis']:
        required=api['parameters'].get('required', [])
        tool = {
            "type": "function",
            "function": {
                "name": api['name'],
                "description": api['description'],
                "parameters": {
                    "type": "object",
                    "properties": {},
                    # "required": [parameters for parameters in api['parameters']['properties'].keys()],  # 确保 required 存在
                    "required": api['parameters']['required'],  # 确保 required 存在
                    "additionalProperties": True
                },
                "strict": False
            }
        }

        # 遍历 parameters 中的 properties
        for param_name, param_info in api['parameters']['properties'].items():
            tool['function']['parameters']['properties'][param_name] = {
                # "type": param_info['type'] if param_name in required else [param_info['type'],"null"],
                "type": param_info['type'],
                "description": param_info['description']
            }
            if param_info['type'] == "tuple":
                tool['function']['parameters']['properties'][param_name]['type'] = "array"
                tool['function']['parameters']['properties'][param_name]['items'] = {
                    "type": "object",
                }
            if param_info['type'] == "array":
                tool['function']['parameters']['properties'][param_name]['items'] = {
                    "type": "object",
                }
            if param_info['type'] == "float":
                tool['function']['parameters']['properties'][param_name]['type'] = "number"
            if param_info['type'] == "dict":
                tool['function']['parameters']['properties'][param_name]['type'] = "object"

        tools.append(tool)

    return tools

def convert_to_qwen_tools_format(test_data):
    tools = []

    for api in test_data['apis']:
        required=api['parameters'].get('required', [])
        tool = {
            "type": "function",
            "function": {
                "name": api['name'],
                "description": api['description'],
                "parameters": {
                    "type": "object",
                    "properties": {},
                    # "required": required,  # 确保 required 存在
                },
            }
        }

        # 遍历 parameters 中的 properties
        for param_name, param_info in api['parameters']['properties'].items():
            tool['function']['parameters']['properties'][param_name] = {
                "type": param_info['type'] if param_name in required else [param_info['type'],"null"],
                "description": param_info['description']
            }

        tools.append(tool)

    return tools

def run_this_function(apis, response):
    if not response.get('tool_calls', []):
        return "没有工具调用"

    # 遍历 response 中的 tool_calls
    for tool_call in response.get('tool_calls', []):
        function_name = tool_call.get('function', {}).get('name')
        function_arguments = tool_call.get('function', {}).get('arguments', '{}')

        # 查找对应的 API 描述
        api = next((api for api in apis if api['name'] == function_name), None)

        if api is None:
            return f"未找到对应的 API 描述: {function_name}"

        # 获取 API 的 required 参数
        required_params = api.get('parameters', {}).get('required', [])

        # 解析 arguments 为字典
        import json
        try:
            arguments_dict = json.loads(function_arguments)
        except json.JSONDecodeError:
            return f"函数 {function_name} 的参数格式不正确"

        # 判断参数值是否有效
        def is_invalid(value):
            return value is None or value == "" or (isinstance(value, (str, list, dict)) and len(value) == 0)

        # 检查是否缺少必需的参数或者值无效
        missing_params = [
            param for param in required_params
            if param not in arguments_dict or is_invalid(arguments_dict[param])
        ]

        if missing_params:
            return f"调用函数 {function_name} 但是缺少或参数值无效: {', '.join(missing_params)}"

        # 如果没有缺少参数，返回已运行函数的消息
        return f"成功运行 {function_name} 函数"

    return "没有找到需要执行的工具调用"

def simulation_tool_use(apis:list, function_name:str, arguments:dict, arguments_desc:dict={})->(bool, str):


    # 查找对应的 API 描述
    api = next((api for api in apis if api['name'] == function_name), None)

    if api is None:
        return False, f"未找到对应的 API 描述: {function_name}"

    # 获取 API 的 required 参数
    required_params = api.get('parameters', {}).get('required', [])

    # 判断参数值是否有效
    def is_invalid(value):
        return value is None or value == "" or (isinstance(value, (str, list, dict)) and len(value) == 0)



    # 检查是否缺少必需的参数或者值无效
    missing_params = [
        param for param in required_params
        if param not in arguments or is_invalid(arguments[param])
    ]

    if missing_params:
        missing_params_desc = [arguments_desc.get(param,param) for param in missing_params]
        return False, f"调用函数 {function_name} 但是缺少参数: {', '.join(missing_params_desc)}"

    # 如果没有缺少参数，返回已运行函数的消息
    return True, f"已经运行 {function_name} 函数"

def convert_to_targets_format(response):
    if response['tool_calls'] is None:
        return []
    res = []
    for tool_call in response['tool_calls']:
        try:
            res.append({"name":tool_call['function']['name'],
             "arguments":json.loads(tool_call['function']['arguments'])})
        except Exception as e:
            print("error: "+str(e))

    return res